package com.fruit.api.controller.fruit;

import com.fruit.bean.dto.fruit.FruitSellRequestDto;
import com.fruit.bean.dto.fruit.FruitSellRequestInfoDto;
import com.fruit.bean.entity.fruit.FruitOnShelfDto;
import com.fruit.bean.entity.fruit.FruitSellRequestInfo;
import com.fruit.bean.entity.fruit.FruitStockInfo;
import com.fruit.bean.enumeration.fruit.FruitSellReqResEnum;
import com.fruit.bean.vo.front.Rets;
import com.fruit.service.fruit.FruitSellRequestService;
import com.fruit.service.fruit.FruitShelfService;
import com.fruit.service.fruit.FruitStockService;
import com.fruit.utils.BeanUtil;
import com.fruit.utils.BigDecimalUtils;
import com.fruit.utils.factory.Page;
import com.fruit.warpper.UserWarpper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 代卖相关接口
 */
@RestController
@RequestMapping("/fruit/sell/request")
public class FruitSellRequestController {

    @Autowired
    private FruitSellRequestService fruitSellRequestService;

    @Autowired
    private FruitShelfService fruitShelfService;

    @Autowired
    private FruitStockService stockService;

    /**
     * 新增代卖申请
     *
     * @return
     */
    @RequestMapping("/add")
    public Object sendSellRequest(@RequestBody FruitSellRequestDto sellRequestDto) {
        FruitSellRequestInfo fruitSellRequestInfo = new FruitSellRequestInfo();
        fruitSellRequestInfo.setFruitStockId(sellRequestDto.getFruitStockId());
        fruitSellRequestInfo.setFruitHighPrice(sellRequestDto.getSellHighPrice());
        fruitSellRequestInfo.setFruitLowPrice(sellRequestDto.getSellLowPrice());
        fruitSellRequestInfo.setFruitSellPrice(sellRequestDto.getSellPrice());
        fruitSellRequestInfo.setFruitSellNumber(sellRequestDto.getSellNumber());
        fruitSellRequestInfo.setFruitSellRequestTime(new Date());
        fruitSellRequestInfo.setUserId(sellRequestDto.getUserId());
        fruitSellRequestInfo.setFruitSellRequestResult(FruitSellReqResEnum.NEGOTIATING.getCode());
        return fruitSellRequestService.addSellRequest(fruitSellRequestInfo);
    }

    /**
     * 同意代卖申请
     *
     * @return
     */
    @PostMapping("/accept")
    public Object acceptSellRequest(@RequestParam Long sellRequestId,
                                    @RequestParam Double sellPrice) {
        FruitSellRequestDto sellRequestDto = new FruitSellRequestDto();
        sellRequestDto.setSellPrice(sellPrice);
        sellRequestDto.setSellRequestId(sellRequestId);
        FruitSellRequestInfo sellRequestInfo = fruitSellRequestService.get(sellRequestDto.getSellRequestId());
        sellRequestInfo.setFruitSellPrice(sellRequestDto.getSellPrice());
        sellRequestInfo.setFruitSellRequestResult(FruitSellReqResEnum.ACCEPT.getCode());
        sellRequestInfo.setFruitSellRequestTime(new Date());
        fruitSellRequestService.update(sellRequestInfo);
        return Rets.success();
    }

    /**
     * 拒绝代卖申请（管理员拒绝代卖）
     * @return
     */
    @PostMapping("/refuse")
    public Object refuseSellRequest(@RequestParam Long sellRequestId) {
        FruitSellRequestInfo fruitSellRequestInfo = fruitSellRequestService.get(sellRequestId);
        fruitSellRequestInfo.setFruitSellRequestResult(FruitSellReqResEnum.REFUSE.getCode());
        return Rets.success(fruitSellRequestService.update(fruitSellRequestInfo));
    }

    /**
     * 取消代卖申请（果农果商取消代卖）
     *
     * @return
     */
    @RequestMapping("/cancel")
    public Object cancelSellRequest(@RequestBody Map<String, Long> map) {
        Long sellRequestId = map.get("sellRequestId");
        FruitSellRequestInfo fruitSellRequestInfo = fruitSellRequestService.get(sellRequestId);
        fruitSellRequestInfo.setFruitSellRequestResult(FruitSellReqResEnum.CANCEL.getCode());
        return Rets.success(fruitSellRequestService.update(fruitSellRequestInfo));
    }

    /**
     * 商户确认代卖
     *
     * @return
     */
    @RequestMapping("/confirm")
    public Object confirmSellRequest(@RequestBody FruitOnShelfDto fruitOnShelfDto) {
        FruitSellRequestInfo fruitSellRequestInfo = fruitSellRequestService.get(fruitOnShelfDto.getSellRequestId());
        fruitSellRequestInfo.setFruitSellRequestResult(FruitSellReqResEnum.CONFIRM.getCode());
        fruitSellRequestService.update(fruitSellRequestInfo);

        Long fruitStockInfoId = fruitSellRequestInfo.getFruitStockId();
        FruitStockInfo fruitStockInfo = stockService.get(fruitStockInfoId);
        //上架完成修改库存
        fruitStockInfo.setFruitStockNumber(
                BigDecimalUtils.sub(fruitStockInfo.getFruitStockNumber(),fruitSellRequestInfo.getFruitSellNumber()).doubleValue());
        stockService.update(fruitStockInfo);

        //上架水果
        return Rets.success(fruitShelfService.onShelf(fruitSellRequestInfo.getFruitStockId(),
                fruitSellRequestInfo.getFruitLastPrice(),
                fruitSellRequestInfo.getFruitSellNumber(),
                fruitOnShelfDto));
    }

    @RequestMapping("/uploadFile")
    @ResponseBody
    public Object uploadFile(HttpServletResponse response, HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        try {
            String uuid = UUID.randomUUID().toString();
            String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).toLowerCase();
            File targetFile = new File("D:\\temp\\images\\"+uuid + type);
            if (!targetFile.exists()) {
                targetFile.createNewFile();
            }
            file.transferTo(targetFile);
            return "http://localhost:8091/"+uuid + type;
        } catch (Exception e) {
            return "上传失败";
        }
    }

    /**
     * 管理员获取代卖申请列表，如果是管理员用户则获取全部的代卖列表
     * 默认按照：申请中，接受，
     *
     * @return
     */
    @GetMapping("/list")
    public Object listSellRequest() {
        Page page = fruitSellRequestService.list();
        List list = (List) new UserWarpper(BeanUtil.objectsToMaps(page.getRecords())).warp();
        page.setRecords(list);
        return Rets.success(page);
    }

    /**
     * 商户获取代卖申请列表
     *
     * @return
     */
    @PostMapping("/mylist")
    public Object listSellRequest(@RequestBody Map<String, Long> map) {
        Long userId = map.get("userId");
        List<FruitSellRequestInfoDto> sellRequestDtoList = fruitSellRequestService.list(userId);
        return Rets.success(sellRequestDtoList);
    }
}
